package com.multimedia.scala.euler

import scala.annotation.tailrec
import com.multimedia.scala.Primes
/*
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?
 */
object Asd41 {
    def main(args : Array[String]) : Unit = {
        def isPandigital(digit: Int) = {
            val digits = digit.toString().toCharArray.map(_.asDigit)
            if (digits.exists(_>digits.size)) false
            else digits.distinct.size==digits.size
        }

        @tailrec
        def findSimplePandigit(size: Int = 9): Int = {
            if (size < 1) return -1
            println(size)
            //the max length of pandigital is 9 so max divisor is
            val maxDivisor = Math.pow(987654321.0, 0.5).toInt + 1
            val simples = Primes.findSimples(maxDivisor)
            
            def createPandigits(size: Int) = (1 to size).reverse
            def isSimple(digit: Int) = !simples.exists(digit%_==0)

            createPandigits(size).permutations.map(_.map(_.toString).reduce(_ + _)).map(_.toInt)
            .find(isSimple) match {
              case Some(x) => return x
              case None => return findSimplePandigit(size-1)
            }
        }
        println(findSimplePandigit())
        /*List(1, 2, 3, 5).find(2==) match {
          case Some(x) => println(7)
          case None => println("not found")
        }*/
    }
}
